package com.zz.rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author zz
 * @Date 2022/5/14
 *
 * 传输类
 */

public class RpcNetTransport {

    private String host;
    private int port;

    public RpcNetTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private Socket newSocket() throws IOException {
        System.out.println("开始建立一个客户端连接");
        Socket socket=new Socket(host,port);
        return socket;
    }

    public Object send(RpcReequest reequest) throws IOException, ClassNotFoundException {
        Socket socket;
        ObjectInputStream objectInputStream=null;
        ObjectOutputStream objectOutputStream=null;
        Object result=null;
        try {
            socket=newSocket();
            //objectInputStream=new ObjectInputStream(socket.getInputStream());
            objectOutputStream=new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(reequest);
            objectOutputStream.flush();
            //获取服务端响应结果
            /**
             * 这里必须获取一次输入流，且不可以提前获取
             */
            objectInputStream=new ObjectInputStream(socket.getInputStream());
            result=objectInputStream.readObject();

        }catch (Exception e){
            throw e;
        }finally {
            if(objectInputStream!=null){
                objectInputStream.close();
            }
            if(objectOutputStream!=null){
                objectOutputStream.close();
            }
        }
        return result;
    }
}
